<template>
	<div class="padding-across-10" :element-loading-text="loadingText" v-loading.fullscreen.lock="pushLoading">
		<div class="list">
			<p class="panel_title">区域列表</p>
			<el-tree :show-overflow-tooltip="true" style="height: 450px;overflow: auto;border: 0" ref="tree" :data="districtsDatas" :props="defaultProps" node-key="DistrictKeyId" :current-node-key="currentNodeKey" :highlight-current="true" :default-expanded-keys="defaultExpandedKeys" :expand-on-click-node="false" @node-click="handleNodeClick">
			</el-tree>
		</div>
		<div style="width:85%;float:right">
			<div style="width: 100%;padding-bottom: 3px">
				<el-row>
					<el-col :span="10">
						<headerOpreate :opreate-datas="opreateDatas" v-on:executeAction="executeAction"></headerOpreate>
					</el-col>
					<el-col :span="14">
						<div style="text-align: right">
							<span style="font-size: 13px;font-weight: bold">设备种类</span>
							<el-select style="width: 140px" size="small" v-model="deviceType" placeholder="请选择设备类型" @change="selectDeviceType">
								<el-option v-for="item in deviceTypeDatas" :key="item.name" :label="item.value" :value="item.name">
								</el-option>
							</el-select>
						</div>
					</el-col>
				</el-row>
			</div>
			<div style="width: 100%">
				<div style="float: left;padding-top: 10px">
					<span style="font-size: 15px;font-weight: bold"><i style="color: red" class="el-icon-warning el-icon--left"></i>此页面仅显示当前在线设备</span>
				</div>
				<div class="block" style="text-align:right;float: right;padding: 5px 0 0">
					<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes,prev, pager, next, jumper" :total="totalSize">
					</el-pagination>
				</div>
			</div>
			<el-table v-loading="loading" element-loading-text="拼命加载中" border style="width: 100%;" :data="tableData">
				<el-table-column label="" width="50">
					<template slot-scope="scope">
						<el-radio :label="scope.row.sn" v-model="checkForm.sn" @change.native="getCurrentRow(scope.row)">&nbsp;</el-radio>
					</template>
				</el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="设备名" align="center" prop="name"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="设备码" align="center" prop="sn"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="型号" align="center" prop="model"></el-table-column>
				<!-- <el-table-column label="位置" align="center"></el-table-column> -->
				<el-table-column :show-overflow-tooltip="true" label="状态" align="center">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.online" type="success">
							<li class="el-icon-circle-check el-icon--left"></li>在线
						</el-tag>
						<el-tag v-else type="gray">
							<li class="el-icon-circle-close el-icon--left"></li>离线
						</el-tag>
					</template>
				</el-table-column>
			</el-table>
			<div class="block" style="text-align:right;margin-bottom:60px;">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes,prev, pager, next, jumper" :total="totalSize">
				</el-pagination>
			</div>
		</div>
		<!--固件升级弹窗-->
		<pushFirDialog ref="push-fir-dialog" :titles="titles" :select-warning="selectWarning" :list-title="listTitle" :push-data="firmwareData" :props="props" v-on:pushSubmit="pushSubmit"></pushFirDialog>
		<!--APK升级弹窗-->
		<pushFirDialog ref="push-apk-dialog" :titles="titles" :select-warning="selectWarning" :list-title="listTitle" :push-data="apkData" :props="props" v-on:pushSubmit="pushSubmit"></pushFirDialog>

		<el-dialog :visible.sync="progressDialog" id="img-diglog" :class="[dialog-large-width]" :show-close="false">
			<el-progress type="circle" :percentage="downloadProgress"></el-progress>
		</el-dialog>
	</div>
</template>
<script>
	import $ from 'jquery'
	import { GloabFun, HttpServer } from '../../../../assets/js/common.js'
	import headerOpreate from '../../../../components/headerOpreate'
	import pushFirDialog from '../../../../components/pushFirDialog'
	let id = 1000;
	export default {
		components: {
			headerOpreate,
			pushFirDialog
		},
		data() {
			return {
				progressDialog: false,
				downloadProgress: 0,
				isReload: false,
				deviceTypeDatas: [],
				deviceType: '',
				checkForm: {
					sn: '',
					version: '',
					model: '',
					type: 0 
				},
				titles: '',
				currentNodeKey: null,
				districtsDatas: [],
				defaultExpandedKeys: [],
				loading: false,
				data: [],
				dynamicTags: [],
				inputVisible: false,
				inputValue: '',
				tableData: [],
				pushLoading: false,
				loadingText: '',
				districtForm: {
					districtid: ''
				},
				defaultProps: {
					children: 'Children',
					label: 'Name',
					id: 'Id'
				},
				multipleSelection: [],
				currentPage: 1,
				pageSize: 10,
				totalSize: 0,
				opreateDatas: [{
					show: true,
					size: "small",
					type: 'primary',
					icon: 'el-icon-eleg-icon_refresh el-icon--left',
					name: this.$t("message.refresh"),
					action: 'reloadDatas'
				}, {
					show: GloabFun.getUid() == 'admin' ? true : false,
					size: "small",
					type: 'primary',
					icon: 'el-icon-eleg-icon_drive_alt el-icon--left',
					name: '更新固件',
					action: 'firmwareUpdate'
				},
				{
					show: GloabFun.getUid() == 'admin' ? true : false,
					type: "primary",
					size: "small",
					icon: "el-icon-eleg-icon_upload el-icon--left",
					name: "更新APK",
					action: "apkUpdate"
				}
				],
				selectWarning: '',
				listTitle: '',
				firmwareData: [],
				apkData: [],
				//推送对象
				pushObj: {
					name: '',
					url: '',
					desc: '',
					type: '',
					waitting: false,
					receiveCMD: false,
					loopCount: 6,
					currentCount: 0,
					startLoop: function(fn) {
						return setInterval(fn, 2000);
					},
					loopRequest: null
				},
				loopArray: [],
			}
		},
		props: {
			subArgs: {
				type: Object,
				default: function() {
					return {};
				}
			}
		},
		methods: {
			executeAction(action) {
				if(action) {
					this[action]();
				}
			},


			backPrev() {
				this.$emit('backPrev');
			},
			backNav(item) {},
			//勾选框初始化
			checkboxInit(row, index) {
				if(row.online) {
					return 1;
				} else {
					return 0;
				}
			},
			//单选
			getCurrentRow(row) {
				this.checkForm.sn = row.sn;
				this.checkForm.model = row.model;
				//获取设备版本号
				HttpServer.httpPost.call(this, '/api/bookracks/allInfo', {
					sn: this.checkForm.sn
				}, function(response) {}, function(response) {
					if(response.data.code === 0) {
						if(response.data.status != null){
							this.checkForm.version = response.data.status.appver;
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				})
			},
			//选择区域
			handleNodeClick(data) {
				this.districtForm.districtid = data.DistrictKeyId;
				this.findDistrictDevices();
			},
			//选择设备种类
			selectDeviceType() {
				this.findDistrictDevices();
			},
			//固件推送
			firmwareUpdate() {
				if(this.checkForm.sn != ''){
					this.getFirmware();
					this.checkForm.type = 2;
					this.titles = '请选择升级的固件';
				}else {
					this.$notify.warning({
						title: '提示',
						message: '请选择升级设备',
						duration: 2500
					});
				}
			},
			//APK升级
			apkUpdate() {
				if(this.checkForm.sn != ''){
					this.getAPKData();
					this.checkForm.type = 1;
					this.titles = '请选择升级的APK';
				}else {
					this.$notify.warning({
						title: '提示',
						message: '请选择升级设备',
						duration: 2500
					});
				}	
			},
			//通过cmdid查询下载安装过程
			getProgress(str) {
				var that = this;
				this.progressInterval = setInterval(() => {
					HttpServer.httpGet.call(this,'/Api/Peripheral/GetUpgradeProgress?cmdid=' + str, function(resp){}, function(resp){
						if(resp.data.code === 0){
							if(resp.data.isdone === 0){
								if(resp.data.downprogress != 1){
									that.loadingText = '正在下载，下载进度：' + resp.data.downprogress * 100 + '%';
								}else {
									that.loadingText = '正在安装，请稍后...';
								}
							}else if(resp.data.isdone === 1){
								that.pushLoading = false;
								that.$notify({
									title: '成功',
									message: that.checkForm.type === 1 ? 'APK安装成功' : '固件安装成功',
									type: 'success',
									duration: 2500
								});
								clearInterval(that.progressInterval);
							}else if(resp.data.isdone === -1){
								that.pushLoading = false;
								clearInterval(that.progressInterval);
								if(resp.data.downprogress != 1){
									that.$notify.error({
										title: '错误',
										message: that.checkForm.type === 1 ? 'APK下载失败' : '固件下载失败',
										duration: 2500
									});
								}else {
									that.$notify.error({
										title: '错误',
										message: that.checkForm.type === 1 ? 'APK安装失败' : '固件安装失败',
										duration: 2500
									});
								}	
							}
						}else {
							that.pushLoading = false;
							clearInterval(that.progressInterval);
							that.$notify.error({
								title: '错误',
								message: resp.data.msg,
								duration: 2500
							});
						}
					})
				},2000);
			},
			//推送
			pushSubmit(obj) {
				// if(this.deviceType == 'WeiTu' || this.deviceType == 'BookCorner' || this.deviceType == 'Self_ServiceMachine'){
				// 	this.loadingText = '准备更新';
				// }else {
				// 	this.loadingText = '设备升级中，请稍后...';
				// }
				this.loadingText = '准备更新';
				this.pushLoading = true;
				var paramContent = {
					device: [
					{
						sn: this.checkForm.sn,
						version: this.checkForm.version
					}
					],
					category:this.deviceType,
					type: this.checkForm.type,
					name: obj.data.name,
					url: obj.data.url,
					msg: obj.Reason,
					Dsc: obj.data.desc,
					UserId: parseInt(GloabFun.getKeyId())
				}
				HttpServer.httpPost.call(this, '/Api/Peripheral/Upgrade', paramContent, function(response) {}, function(response) {
					// if(this.deviceType == 'WeiTu' || this.deviceType == 'BookCorner' || this.deviceType == 'Self_ServiceMachine'){
						if(response.data.code === 0){
							this.getProgress(response.data.cmdid);
						} else {
							this.pushLoading = false;
							this.$notify.error({
								title: '错误',
								message: response.data.msg,
								duration: 2500
							});
						}
					// }else {
					// 	this.pushLoading = false;
					// 	if(response.data.code === 0){
					// 		if(response.data.response.length > 0) {
					// 			if(response.data.response[0].sn === this.checkForm.sn && response.data.response[0].code === 0) {
					// 				this.$notify({
					// 					title: '成功',
					// 					message: '设备升级成功',
					// 					type: 'success',
					// 					duration: 2500
					// 				});
					// 			} else {
					// 				this.$notify.error({
					// 					title: '错误',
					// 					message: response.data.response[0].msg,
					// 					duration: 2500
					// 				});
					// 			}
					// 		} else {
					// 			this.$notify.error({
					// 				title: '错误',
					// 				message: '升级失败',
					// 				duration: 2500
					// 			});
					// 		}
					// 	}else {
					// 		this.$notify.error({
					// 			title: '错误',
					// 			message: response.data.msg,
					// 			duration: 2500
					// 		});
					// 	}
					// }
				});
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.findDistrictDevices();
			},
			handleSizeChange(val) {
				this.pageSize = val;
				this.findDistrictDevices();
			},
			//去掉时间中的T
			formateData(array) {
				for(var i = 0; i < array.length; i++) {
					var index1 = array[i].time.indexOf("T");
					array[i].time = array[i].time.substring(0, index1) + " " + array[i].time.substring(index1 + 1, index1 + 9);
				}
			},
			getFirmware() {
				this.firmwareData = [];
				this.selectWarning = '请选择固件';
				this.listTitle = '固件列表';
				var param = {
					type: 4,
					types: [],
					devicetype: this.deviceType
				}
				HttpServer.httpPost.call(this, '/Api/User/File/CommonFileInfo', param, function(response) {}, function(response) {
					// console.log('固件资源列表', response);
					if(response.data.code === 0) {
						this.formateData(response.data.Info_);
						this.firmwareData = response.data.Info_;
						this.$refs['push-fir-dialog'].showDialog();
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				});
			},
			getAPKData() {
				this.apkData = [];
				this.selectWarning = '请选择APK';
				this.listTitle = 'APK列表';
				var param = {
					type: 1,
					types: [],
					devicetype: this.deviceType
				}
				HttpServer.httpPost.call(this, '/Api/User/File/CommonFileInfo', param, function(response) {}, function(response) {
					// console.log('apk文件列表', response);
					if(response.data.code === 0) {
						this.formateData(response.data.Info_);
						this.apkData = response.data.Info_;
						this.$refs['push-apk-dialog'].showDialog();
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				});
			},
			//查询指定区域下的在线设备
			findDistrictDevices() {
				this.loading = true;
				HttpServer.httpPost.call(this, '/Api/District/GetDevices', {
					userKeyId: GloabFun.getKeyId(),
					districtid: this.districtForm.districtid,
					index: this.currentPage,
					pagesize: this.pageSize,
					isonline: 1,
					category: [this.deviceType],
					model: []
				}, function(res) {}, function(res) {
					this.loading = false;
					this.tableData = [];
					if(res.data.code === 0) {
						if(res.data.info.length > 0){
							this.checkForm.sn = res.data.info[0].sn;
							this.checkForm.model = res.data.info[0].model;
							this.tableData = res.data.info;
							this.totalSize = res.data.totalcount;
						}
						if(this.isReload){
							this.$notify({
								title: '成功',
								message: this.$t('message.refreshSuccess'),
								type: 'success',
								duration: 2500
							});
						}
					} else {
						this.tableData = [];
						this.totalSize = 0;
						this.$notify.error({
							title: '错误',
							message: res.data.msg,
							duration: 2500
						});
					}
					this.isReload = false;
				});
			},
			//刷新
			reloadDatas() {
				this.isReload = true;
				this.findDistrictDevices();
			},
			sortDatas(arr) {
				for(var i=0;i<arr.length;i++){
					for(var j = i + 1;j<arr.length;j++){
						if(arr[i].DistrictKeyId>arr[j].DistrictKeyId){
							var tmp = arr[i];
							arr[i] = arr[j];
							arr[j] = tmp;
						}
					}
				}
				return arr;
			},
			//默认查询,用于左侧树状图展示
			getDatas() {
				//查询用户绑定区域
				HttpServer.httpGet.call(this, '/Api/District/districtTree?uid=' + GloabFun.getKeyId(), function(response) {}, function(response) {
					// console.log('获取当前用户的所有绑定区域信息',response)
					if(response.data.code === 0) {
						if(response.data.info.length > 0) {
							this.districtsDatas = this.sortDatas(response.data.info);
							this.defaultExpandedKeys.push(this.districtsDatas[0].DistrictKeyId);
							this.currentNodeKey = this.districtsDatas[0].DistrictKeyId;
							//默认查询第一个区域下的在线设备
							this.districtForm.districtid = this.districtsDatas[0].DistrictKeyId;
							HttpServer.httpGet.call(this, '/Api/Device/GetAllDeviceCategory?fromwhat=1', function(response) {}, function(response) {
								this.deviceTypeDatas = response.data;
								this.deviceType = this.deviceTypeDatas[0].name;
							})
							this.findDistrictDevices();
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				});
			}
		},
		created() {
			this.getDatas();
		},
		beforeDestroy() {
			clearInterval(this.progressInterval);
		},
	}
</script>
<style scoped>
	@import '../../../../assets/css/font-awesome-4.7.0/css/font-awesome.css';
</style>
<style lang="less" scope>
	#img-diglog {
		text-align: center;
		.el-dialog {
			background: none;
			box-shadow: none;
		}
		.el-dialog__body {
			overflow: visible !important;
		}
	}
</style>
<style scoped lang="less">
	.name {
		color: #20a0ff;
	}
	
	.list {
		height: 500px;
		// max-height:580px;
		width: 14%;
		float: left;
		overflow: auto;
		// padding-top: 10px;
		// background-color: #324157;
		margin-bottom: 10px;
		.panel_title {
			height: 28px;
			line-height: 28px;
			font-size: 15px;
			text-align: center;
			border: 1px solid #E0E0E0;
			border-radius: 5px;
			color: #fff;
			background-color: #324157;
		}
		// color:#fff
	}
</style>